﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Configuration;

namespace DtuService
{
    class ServerMain 
    {
        private static ServerMain _instance;
        private long start_time;
        private bool serverShutdown = false;
        public static ServerMain Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ServerMain();
                }
                return _instance;
            }
        }
        
        public static string FileDirectory;
        private bool isInitilised;
        private WriteLog writeLog;
        private static object m_threadObj = new object();
        public Configuration Config;
        public Dictionary<string, IServer> ServerList = new Dictionary<string, IServer>();
        public Dictionary<string, IService> ServiceList = new Dictionary<string, IService>();
        public Tools CommonTools = new Tools();

        private ServerMain()
        {
            
        }

        private void setUpService()
        {
            Console.WriteLine("...初始化服务器设置...");
            initilised();          
            ServerList.Add(typeof(TCPServer).FullName, System.Activator.CreateInstance<TCPServer>());
            ServerList.Add(typeof(HttpServer).FullName, System.Activator.CreateInstance<HttpServer>());  
            ServerList.Add(typeof(CacheServer).FullName, System.Activator.CreateInstance<CacheServer>());
            ServerList.Add(typeof(MessageServer).FullName, System.Activator.CreateInstance<MessageServer>());

            ServiceList.Add(typeof(UserService).FullName, System.Activator.CreateInstance<UserService>());
            ServiceList.Add(typeof(DeviceService).FullName, System.Activator.CreateInstance<DeviceService>());
        }

        private void setUpDataBase()
        {
            Console.WriteLine("...初始化数据库...");
            string sqlServerName = Config.AppSettings.Settings["DataServerName"].Value;
            string dbName = Config.AppSettings.Settings["DataBaseName"].Value;
            string id = Config.AppSettings.Settings["DataBaseUser"].Value;
            string pwd = Config.AppSettings.Settings["DataBasePassword"].Value;
            Console.WriteLine(DataAccess.data.InitDataBase(sqlServerName, dbName, id, pwd));
            Busness.Business.getInstance().Init();

        }

        /// <summary>
        /// 开启服务
        /// </summary>
        /// <returns></returns>
        public bool StartServer()
        {
            setUpService();
            setUpDataBase();
            foreach (KeyValuePair<string, IServer> svr in ServerList)
            {
                svr.Value.Init();
            }
            foreach (KeyValuePair<string, IService> svi in ServiceList)
            {
                svi.Value.Init();
            }
            start_time = CommonTools.GetTimeStamp();
            return true;
        }

        public static T GetService<T>()
        {
            string key = typeof(T).FullName;
            if (!Instance.ServiceList.ContainsKey(key))
            {
                return default(T);
            }
            return (T)Instance.ServiceList[key];
        }

        public static T GetServer<T>()
        {
            string key = typeof(T).FullName;
            if (!Instance.ServerList.ContainsKey(key))
            {
                return default(T);
            }
            return (T)Instance.ServerList[key];
        }

        /// <summary>
        /// 主逻辑循环
        /// </summary>
        public void ServerRun()
        {
            try
            {
                foreach (KeyValuePair<string, IServer> svr in ServerList)
                {
                    svr.Value.Tick(0.01f);
                }
                foreach (KeyValuePair<string, IService> svi in ServiceList)
                {
                    svi.Value.Tick(0.01f);
                }
            }
            catch (Exception ex)
            {
                Debug.Log(ex.ToString());
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void initilised()
        {
            if (isInitilised == true)
            {
                return;
            }
            Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string logDir = Config.AppSettings.Settings["logTcpDirection"].Value;
            //if (TCPORHTTP == 1)
            //{
            //    logDir = Config.AppSettings.Settings["logHttpDirection"].Value;
            //}
            writeLog = new WriteLog(logDir);
            FileDirectory = Config.AppSettings.Settings["FileDirectory"].Value;
            if (FileDirectory == "")
                FileDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Files");
            if (!Directory.Exists(FileDirectory))
                Directory.CreateDirectory(FileDirectory);
            DateTime currentTime = DateTime.Now;
            Debug.WriteLog = writeLog;
            isInitilised = true;
        } 
      
        public void ShutdownServer()
        {
            foreach (KeyValuePair<string, IServer> svr in ServerList)
            {
                svr.Value.ShutDown();
            }
            ServerList.Clear();
            foreach (KeyValuePair<string, IService> service in ServiceList)
            {
                service.Value.Shutdown();
            }
            ServiceList.Clear();
            serverShutdown = true;
        }
    }
}
